//
//  WCGetInfoBuildStepsArrayController.m
//  WabbitCode
//
//  Created by William Towe on 4/17/09.
//  Copyright 2009 Revolution Software. All rights reserved.
//

#import "WCGetInfoBuildStepsArrayController.h"
#import "WCGetInfoBuildStepsTableView.h"


@implementation WCGetInfoBuildStepsArrayController
- (NSDragOperation)tableView:(NSTableView *)tableView validateDrop:(id < NSDraggingInfo >)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)operation {
	// don't allow drops on the row, only between rows
	if (operation == NSTableViewDropOn)
		return NSDragOperationNone;
	
	// if the pasteboard contains our special type it's going to be a move or nothing
	if ([[[info draggingPasteboard] types] containsObject:kWCGetInfoBuildStepsTableViewPboardType]) {
		// we archived an NSIndexSet, unarchive and get the only index
		NSUInteger index = [[NSKeyedUnarchiver unarchiveObjectWithData:[[info draggingPasteboard] dataForType:kWCGetInfoBuildStepsTableViewPboardType]] firstIndex];
		
		// don't allow a drop one row above and one row below the row being dragged
		if (index == row || index == --row)
			return NSDragOperationNone;
		return NSDragOperationMove;
	}
	return NSDragOperationNone;
}

- (BOOL)tableView:(NSTableView *)tableView acceptDrop:(id < NSDraggingInfo >)info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)operation {
	if ([[[info draggingPasteboard] types] containsObject:kWCGetInfoBuildStepsTableViewPboardType]) {
		// we archived an NSIndexSet, unarchive and get the only index
		NSUInteger index = [[NSKeyedUnarchiver unarchiveObjectWithData:[[info draggingPasteboard] dataForType:kWCGetInfoBuildStepsTableViewPboardType]] firstIndex];
		
		// insert the object being dragged at the new index
		[self insertObject:[[self arrangedObjects] objectAtIndex:index] atArrangedObjectIndex:row];
		
		// adjust the index
		if (row <= index)
			++index;
		
		// remove the old object
		[self removeObjectAtArrangedObjectIndex:index];
		return YES;
	}
	return NO;
}

- (BOOL)tableView:(NSTableView *)tableView writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard *)pboard {
	[pboard declareTypes:[NSArray arrayWithObject:kWCGetInfoBuildStepsTableViewPboardType] owner:nil];
	[pboard setData:[NSKeyedArchiver archivedDataWithRootObject:rowIndexes] forType:kWCGetInfoBuildStepsTableViewPboardType];
	return YES;
}
@end
